from conn_mysql_redis import ConnRedis, ConnMysql, InsertConnMysql
from sanic import response
import uuid
import asyncio
import json

class UserLogin_():

    async def user_login(self, phone,verify_code):
        
        if not all([phone,verify_code]):

            return {

                'status': -1,
                'errorCode': 21,
                'errorMsg': '请检查你的参数',
                'resultBody': None
            }
        sql = 'SELECT * from user where user_phone=%s'
        result = await ConnMysql().select_one(sql, (phone,))

        if not result:

            return {

                'status': -1,
                'errorCode': 22,
                'errorMsg': '用户名不存在',
                'resultBody': None

            }


        with await ConnRedis().pool_ as c:
            await c.select(1)
            result_info=await c.get(phone)
            await c.select(0)

        if not result_info:

            return {
                'status': -1,
                'errorCode': 23,
                'errorMsg': '验证码过期',
                'resultBody': None
            }

        if result_info != verify_code:
            
            return {
                'status': -1,
                'errorCode': 24,
                'errorMsg': '验证码输入有误',
                'resultBody': None
            }

        access_token = uuid.uuid1().hex
        
        with await ConnRedis().pool_ as c:

            await c.hmset_dict(access_token, result)
            await c.expire(access_token, 2*3600)

        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': {"info": "登录成功",
                            "access_token": access_token,
                            "user_info":result}}
